package org.example.flinktest;

import java.util.Properties;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.utils.ParameterTool;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer010;
import org.apache.flink.util.Collector;

/**
 * @author SHB
 */
public class MyFirstFlinkDemo {

  public static void main(String[] args) {
    ParameterTool params = ParameterTool.fromArgs(args);

    /*
     * StreamExecutionEnvironment是fink计划的基础，
     * 获取StreamExecutionEnvironment的方法：
     * 通常使用 getExecutionEnvironment()
     * 本地运行测试 createLocalEnvironment()
     * 远程的执行环境createRemoteEnvironment(String host, int port, String... jarFiles)
     */
    final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

    /*
     * DataSet并DataStream在程序中表示数据。您可以将它们视为可以包含重复项的不可变数据集合。
     */
    DataStream<String> stream;
    if (params.has("input")) {
      // 从给定的输入路径读取文本文件
      stream = env.readTextFile(params.get("input"));
    } else {
      System.out.println("使用默认输入数据集执行WordCount示例");
      System.out.println("使用 --input指定文件输入");
      Properties props = new Properties();
      props.setProperty("bootstrap.servers",
          "192.168.7.201:9092,192.168.7.202:9092,192.168.7.203:9092");
      props.setProperty("group.id", "test");
      stream = env
          .addSource(new FlinkKafkaConsumer010<>("test", new SimpleStringSchema(), props));
    }
    stream.flatMap(new FlatMapFunction<String, Tuple2<String,Long>>() {

      @Override
      public void flatMap(String s, Collector<Tuple2<String, Long>> collector) throws Exception {
        for(String word:s.split("\\s")){
          collector.collect(new Tuple2<String, Long>(word, 1L));
        }

      }
    });

  }

}
